package com.example.myapplication.net;

import android.os.Handler;

import java.io.IOException;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.FormBody;
import okhttp3.Headers;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

public class OkHttpUtil {

    private static final OkHttpClient client = new OkHttpClient();

    /**
     * 同步get请求
     * @param url
     * @return
     * @throws Exception
     */
    public static String getUrl(String url) throws Exception {
        Request request = new Request.Builder()
                .url(url)
                .build();
        Response response = client.newCall(request).execute();
        if (!response.isSuccessful()) throw new IOException("Unexpected code " + response);
        Headers responseHeaders = response.headers();
        for (int i = 0; i < responseHeaders.size(); i++) {
            System.out.println(responseHeaders.name(i) + ": " + responseHeaders.value(i));
        }
        return response.body().string();
    }

    /**
     * post请求
     * @param url
     * @return
     * @throws Exception
     */
    public static String postUrl(String url) throws Exception{
        FormBody.Builder requestBodyBuilder = new FormBody.Builder();
        //提交到服务器端的请求体
        RequestBody requestBody = requestBodyBuilder
                .add("page", "1")
                .add("rows", "1")
                .build();

        Request.Builder builder = new Request.Builder();
        Request request = builder
                .url(url)
                .post(requestBody)
                .build();

        Response response = client.newCall(request).execute();
        return response.body().string();
    }

}
